﻿#include"MyMarkDownWidget.h"
#include<QFileDialog>
#include<QMessageBox>
#include<QMenu>
#include<QAction>
#include<QDesktopServices>
void MyMarkdownWidget::openImagePosition()
{
	QDesktopServices::openUrl(QUrl(QString("file:%1").arg(imageDir()), QUrl::TolerantMode));
}

void MyMarkdownWidget::upImage()
{
	auto list = QFileDialog::getOpenFileNames(this, "选择要上传的图像", imageDir(), "Images (*.png *.ico *.jpg *.bmp *.gif)");
	QStringList error;//错误的文件列表
	for (auto& data : list)
	{
		QString newName = QString("%1/%2").arg(imageDir()).arg(QFileInfo(data).fileName());
		if (!QFile::copy(data, newName))
			error << data;
	}
	//qInfo() << error.join("\n");
	if (!list.isEmpty())
		QMessageBox::information(this, "提示", QString("缓存成功:%1 失败:%2\n%3").arg(list.size() - error.size()).arg(error.size()).arg(error.join("\n")));
}
void MyMarkdownWidget::getImageToImageMenu()
{
	//清空上次的
	insertImageMenu->clear();
	QDir dir(imageDir());
	if (!dir.exists())//目录有问题
	{
		return;
	}
	//获取所有的图像文件路径
	auto list = dir.entryInfoList(QDir::Files);
	for (auto& data : list)
	{
		auto action = new QAction(data.fileName(), insertImageMenu);
		//qInfo() << data.absoluteFilePath();
		action->setData(data.absoluteFilePath());
		insertImageMenu->addAction(action);
	}
}
void MyMarkdownWidget::insertImage(QAction* action)
{
	QFileInfo info(action->data().toString());
	m_SourceEdit->textCursor().insertText(QString("    ![%1](%2/%3)").arg(info.baseName()).arg(ImageDirectoryName).arg(info.fileName()));
}

void MyMarkdownWidget::setCursorRow(QTextEdit* edit, const size_t row)
{
	auto widget = focusWidget();
	if (widget == nullptr)return;
	edit->setFocus();
	auto Cursor = edit->textCursor();
	Cursor.movePosition(QTextCursor::Start);
	Cursor.movePosition(QTextCursor::Down, QTextCursor::MoveAnchor, row);
	edit->setTextCursor(Cursor);
	widget->setFocus();
}
